//
//  SWBaseNavigationController.swift
//  BaseDemo
//
//  Created by linhan on 16/2/17.
//  Copyright © 2016年 me. All rights reserved.
//

import Foundation
import UIKit

extension UINavigationController
{
    //屏幕边缘滑动手势
    var screenEdgePanGestureRecognizer:UIGestureRecognizer?
    {
        return view?.gestureRecognizers?.filter({$0 is UIScreenEdgePanGestureRecognizer}).valueAt(0)
    }
}

class SWBaseNavigationController: UINavigationController,UIGestureRecognizerDelegate
{
    private var _navigationBarHidden:Bool = false
    var navigationBarHiddenFlag:Bool
    {
        return _navigationBarHidden
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    private func setup()
    {
        //当自定义导航栏返回按钮、隐藏导航栏时，右滑返回手势就会失效，因此需将手势代理指向自己
        interactivePopGestureRecognizer?.delegate = self
    }
    
    
    override var isNavigationBarHidden: Bool
    {
        get
        {
            return super.isNavigationBarHidden
        }
        set
        {
            if newValue != _navigationBarHidden
            {
                _navigationBarHidden = newValue
                super.isNavigationBarHidden = newValue
            }
        }
    }
    
    //setNavigationBarHidden时如果animated为true，navigationBarHidden的值不会马上改变，
    //如果一个VC中有多个子VC控制导航栏，则会导致重复调用的问题
    override func setNavigationBarHidden(_ hidden: Bool, animated: Bool)
    {
        if hidden != _navigationBarHidden
        {
            _navigationBarHidden = hidden
            super.setNavigationBarHidden(hidden, animated: animated)
        }
    }
    
    override func pushViewController(_ viewController: UIViewController, animated: Bool)
    {
        super.pushViewController(viewController, animated: animated)
        
        //页面push过程中手势返回会导致crash，因此push过程中将手势禁用，完成后再启用
        interactivePopGestureRecognizer?.isEnabled = false
    }
    
    //解决在navigationController的第一个页面右滑返回时，整个界面僵死的BUG
    //因此在第一个页面禁止边缘滑动手势
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool
    {
        var shouldBegin:Bool = true
        if gestureRecognizer is UIScreenEdgePanGestureRecognizer
        {
            if viewControllers.count <= 1
            {
                shouldBegin = false
            }
        }
        return shouldBegin
    }
    
}
